﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Zxb.DayWork.Core;

namespace Zxb.DayWork.Logic
{
    public class PriceSyncWorker:BatchWorker
    {
        /// <summary>
        /// 南北服务器标志位
        ///     0：代表北方服务器，1：代表南方服务器。
        /// </summary>
        private int _nsFlag;
        private string _tempTabName ;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="nsflag">0：代表北方服务器，1：代表南方服务器</param>
        public PriceSyncWorker(int nsflag)
        {
            this._nsFlag = nsflag;
            this._tempTabName = (_nsFlag == 0?"projPriceTempNorth":"projPriceTempSouth");
        }

        protected override void ReadData()
        {
            string sql = "SELECT id,newcode,priceaverage,priceaveragetype from proj_price pp with(nolock) "
                          + "  where pp.id = (select MAX(id) from [proj_price] pp2 with(nolock) "
                          + "      where pp2.newcode = pp.newcode group by pp2.newcode) and pp.id>" + this.GetMaxID();

            Database db = null;
            SqlConnection conn=null;
            try
            {
                if (this._nsFlag == 0)
                {
                    db = DB.EstateReaderNorth;
                }
                else if (_nsFlag == 1)
                {
                    db = DB.EstateReaderSouth;
                }
                DbCommand cmd = db.GetSqlStringCommand(sql);
                DataTable dt = db.ExecuteDataSet(cmd).Tables[0];

                delTab();

                conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ZxbWriter"].ToString());
                conn.Open();

                using (SqlBulkCopy bulk = new SqlBulkCopy(conn))
                {
                    bulk.DestinationTableName = this._tempTabName;
                    bulk.ColumnMappings.Add("id", "id");
                    bulk.ColumnMappings.Add("newcode", "newcode");
                    bulk.ColumnMappings.Add("priceaverage", "priceaverage");
                    bulk.ColumnMappings.Add("priceaveragetype", "priceaveragetype");

                    bulk.BatchSize = 10000;
                    bulk.BulkCopyTimeout = 60;
                    bulk.WriteToServer(dt);
                }
            }
            catch (Exception ex)
            {
                Logger.InfoLog.Error(string.Concat((_nsFlag==0?"北方":"南方")+"楼盘单位价格数据同步"  + "时读取数据出错：", ex.Message));
            }
            finally
            {
                if (conn != null)
                {
                    conn.Close();
                }
            }
        }

        protected override void ProcessData()
        {
            try
            {
                Database db = DB.ZxbWriter;
                StringBuilder upSql = new StringBuilder();
                upSql.Append(" update em ");
                upSql.Append(" set em.AveragePrice = ppt.priceaverage, em.AveragePriceUnit = ppt.priceaveragetype");
                upSql.Append(" from dbo.EstateManage em ");
                upSql.Append(" inner join " + this._tempTabName + " ppt ");
                upSql.Append(" on em.RealEstateID = ppt.newcode ");
                DbCommand upCmd = db.GetSqlStringCommand(upSql.ToString());
                db.ExecuteNonQuery(upCmd);
            }
            catch(Exception ex)
            {
                Logger.InfoLog.Error(string.Concat((_nsFlag == 0 ? "北方" : "南方") + "楼盘单位价格数据同步" + "时更新出错：", ex.Message));
            }
        }

        protected override void WriteData()
        {
            try
            {
                UPMaxID();
            }
            catch (Exception ex)
            {
                Logger.InfoLog.Error(string.Concat((_nsFlag == 0 ? "北方" : "南方") + "楼盘单位价格数据同步" + "时WriteData方法出错：", ex.Message));
            }
        }

        /// <summary>
        /// 获得本次处理最大ID
        /// </summary>
        /// <param name="tempTab"></param>
        /// <returns></returns>
        private int GetMaxID()
        {
            int maxID = 0;
            Database db = DB.ZxbReader;
            string selSql = " select StatusValue from SiteStatus where StatusName = @StatusName";
            DbCommand selCmd = db.GetSqlStringCommand(selSql);
            db.AddInParameter(selCmd, "@StatusName", DbType.String, this._tempTabName);
            DataTable sleDT = db.ExecuteDataSet(selCmd).Tables[0];
            if (sleDT == null || sleDT.Rows.Count <= 0)
            {
                db = DB.ZxbWriter;
                string inSql = " insert SiteStatus values(@StatusName,'0')";
                DbCommand inCmd = db.GetSqlStringCommand(inSql);
                db.AddInParameter(inCmd, "@StatusName", DbType.String, this._tempTabName);
                db.ExecuteNonQuery(inCmd);
            }
            else
            {
                maxID = int.Parse(sleDT.Rows[0]["StatusValue"].ToString());
            }
            return maxID;
        }

        /// <summary>
        /// 更新处理最大ID
        /// </summary>
        /// <param name="StatusName"></param>
        /// <param name="StatusValue"></param>
        private void UPMaxID()
        {
            int todayMaxID = 0;
            Database dbr = DB.ZxbReader;
            string selSql = " select max(id) maxid from " + this._tempTabName;
            DbCommand selCmd = dbr.GetSqlStringCommand(selSql);
            DataTable sleDT = dbr.ExecuteDataSet(selCmd).Tables[0];
            if (sleDT != null && sleDT.Rows.Count >= 1 && !string.IsNullOrEmpty(sleDT.Rows[0]["maxid"].ToString()))
            {
                todayMaxID = int.Parse(sleDT.Rows[0]["maxid"].ToString());
            }
            if (todayMaxID > 0)
            {
                Database db = DB.ZxbWriter;
                string upSql = " update SiteStatus set StatusValue=@StatusValue where StatusName=@StatusName";
                DbCommand upCmd = db.GetSqlStringCommand(upSql);
                db.AddInParameter(upCmd, "@StatusName", DbType.String, this._tempTabName);
                db.AddInParameter(upCmd, "@StatusValue", DbType.String, todayMaxID);
                db.ExecuteNonQuery(upCmd);
            }
        }

        /// <summary>
        /// 删除上次处理过的过期数据
        /// </summary>
        /// <param name="tempTab"></param>
        private void delTab()
        {
            Database db = DB.ZxbWriter;
            string delSql = " delete " + this._tempTabName;
            DbCommand delCmd = db.GetSqlStringCommand(delSql);
            db.ExecuteNonQuery(delCmd);
        }
    }
}
